/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_kit/zhiqim_git.htm
 *
 * ZhiqimGit is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.git.http;

import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.zip.CRC32;

import org.zhiqim.kernel.util.codes.SHA1;

/**
 * 包输出流封装类，实现输出流、校验和摘要同步更新
 *
 * @version v1.0.0 @author zouzhigang 2017-4-20 新建与整理
 */
public final class UploadOutputStream extends OutputStream
{
    private final OutputStream out;                         //原输出流
    private final CRC32 crc = new CRC32();                  //校验
    private final MessageDigest md = SHA1.getInstance();    //摘要
    private long count;

    public UploadOutputStream(final OutputStream out)
    {
        this.out = out;
    }

    @Override
    public void write(final int b) throws IOException
    {
        out.write(b);
        crc.update(b);
        md.update((byte) b);
        count++;
    }

    @Override
    public void write(final byte[] b, final int off, final int len) throws IOException
    {
        out.write(b, off, len);
        crc.update(b, off, len);
        md.update(b, off, len);
        count += len;
    }

    @Override
    public void flush() throws IOException
    {
        out.flush();
    }

    public long length()
    {
        return count;
    }

    public int getCRC32()
    {
        return (int) crc.getValue();
    }

    public void resetCRC32()
    {
        crc.reset();
    }

    public byte[] getDigest()
    {
        return md.digest();
    }
}
